package com.zxjbyte.yiyi.server.annotation;

import com.zxjbyte.yiyi.framework.common.enums.ExtensionBundles;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.filter.AnnotationTypeFilter;

import java.util.Arrays;
import java.util.Map;

/**
 * @Author zhangxingjia
 * @Date 2025/3/20 10:58
 * @Version: 1.0
 */
@Slf4j
public class ExtensionBundlesBeanRegistrar implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry, BeanNameGenerator importBeanNameGenerator) {
        Map<String, Object> attributes = importingClassMetadata.getAnnotationAttributes(EnableExtensionBundles.class.getName());
        if (attributes == null) {
            return;
        }

        ExtensionBundles[] bundles = (ExtensionBundles[]) attributes.get("value");
        ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(registry, false);
        // 允许扫描 @Component、@Service、@Controller 等
        scanner.addIncludeFilter(new AnnotationTypeFilter(org.springframework.stereotype.Component.class));
        scanner.addIncludeFilter(new AnnotationTypeFilter(org.springframework.web.bind.annotation.RestController.class));
        scanner.addIncludeFilter(new AnnotationTypeFilter(org.apache.ibatis.annotations.Mapper.class));

//        scanner.addIncludeFilter((metadataReader, metadataReaderFactory) -> true);

        // 扫描指定的包
        for (ExtensionBundles extensionBundles : bundles) {
            scanner.scan(extensionBundles.getBasePackage());
        }

        log.info(">>>>> Project initialization started. The following features have been enabled and registered: {}", Arrays.toString(bundles));
    }
}
